package com.aruba.attendance.ui.dialog

import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.window.Dialog
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest

/**
 * 展示打卡照片的dialog
 * Created by aruba on 2023/2/16.
 */
@Composable
fun PictureDialog(
    showPictureDialog: PictureDialogState,
    onDismissRequest: (() -> Unit) = { showPictureDialog.dismiss() }
) {
    if (!showPictureDialog.showPictureDialog.value) return

    Dialog(onDismissRequest = { onDismissRequest.invoke() }) {
        var rotationState by remember { mutableStateOf(0f) }
        var scaleState by remember { mutableStateOf(1f) }

        val painter = rememberAsyncImagePainter(
            model = ImageRequest.Builder(LocalContext.current)
                .data(showPictureDialog.path)
                .crossfade(true)
                .build()
        )

        Image(
            painter = painter,
            contentDescription = "pictureDialogImage",
            modifier = Modifier
                .fillMaxSize()
                .scale(scaleState)
                .rotate(rotationState)
                .pointerInput(Unit) {
                    // 监听变换触摸
                    detectTransformGestures { centroid: Offset, pan: Offset, zoom: Float, rotation: Float ->
                        rotationState += rotation / 2f
                        val newScaleState = scaleState * zoom
                        scaleState = run {
                            if (newScaleState <= 0.75f) 0.75f
                            else if (newScaleState >= 5f) 5f
                            else newScaleState
                        }
                    }
                }
                .pointerInput(Unit) {
                    // 监听点击触摸
                    detectTapGestures(onDoubleTap = {
                        scaleState = if (scaleState >= 2f) 1f else 2f
                    }, onTap = {
                        showPictureDialog.dismiss()
                    })
                }
        )
    }
}